package com.tt.utils.wordUtils.utils;

import com.deepoove.poi.data.PictureRenderData;
import com.tt.utils.wordUtils.renderplicy.PoiPictureUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @Title: BaseWordUtiils
 * @Author zl
 * @Package com.oberyun.goHAZOP.utils.wordUtils.utils
 * @Date 2025/9/17 17:43
 * @description: 公用方法
 */

public class BaseWordUtiils {
    /**
     * 添加外部超链接
     *
     * @param url
     * @param text
     * @param paragraph
     */
    public static void appendExternalHyperlink(final String url, final String text, final XWPFParagraph paragraph) {
        if (StringUtils.isBlank(url)) {
            return;
        }

        // 1. 添加外部超链接关系
        String id = paragraph.getDocument()
                .getPackagePart()
                .addExternalRelationship(url, XWPFRelation.HYPERLINK.getRelation())
                .getId();

        // 2. 在段落里新增 <w:hyperlink> 并绑定关系 id
        CTHyperlink cLink = paragraph.getCTP().addNewHyperlink();
        cLink.setId(id);

        // 3. 在 hyperlink 里新建一个 run
        CTR ctr = cLink.addNewR();

        // 4. 用 XWPFHyperlinkRun 包装 CTR，这样可以用常规 API 设置文本和样式
        XWPFHyperlinkRun hyperlinkRun = new XWPFHyperlinkRun(cLink, ctr, paragraph);
        hyperlinkRun.setText(text);
        hyperlinkRun.setColor("0000FF");
        hyperlinkRun.setUnderline(UnderlinePatterns.SINGLE);
        hyperlinkRun.setFontFamily("Calibri");
        hyperlinkRun.setFontSize(12);
    }

    /**
     * 添加图片
     *
     * @param content
     * @param run
     */
    public static void appendImage(Object content, XWPFRun run) {
        PictureRenderData smartPicture = PoiPictureUtils.createSmartPicture(content, PoiPictureUtils.PictureSourceType.URL);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(smartPicture.readPictureData());
        try {
            // 自动按比例缩放到 150 宽度
            BufferedImage img = ImageIO.read(new ByteArrayInputStream(smartPicture.readPictureData()));
            int width = img.getWidth();
            int height = img.getHeight();
            int targetWidth = 80;
            int targetHeight = (int) ((double) targetWidth / width * height);
            run.addPicture(byteArrayInputStream, smartPicture.getPictureType().type(), content.toString(), Units.toEMU(targetWidth), Units.toEMU(targetHeight));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayInputStream.close();
            } catch (IOException ignored) {
            }
        }
    }

}
